#include"string.h"
namespace K
{
	void string::reserve(size_t n)
	{
		if (n > _capacity)
		{
			char* tmp = new char[n + 1];
			strcpy(tmp, _str);
			delete[] _str;
			_str = tmp;
			_capacity = n;
		}
	}
	void string::push_back(char ch)
	{
		if (_size == _capacity)
		{
			reserve(_capacity == 0 ? 4 : _capacity * 2);
		}
		_str[_size++] = ch;
		_str[_size] = '\0';
	}
	string& string::operator+=(char ch)
	{
		push_back(ch);
		return *this;
	}
	void string::append(const char* str)
	{
		size_t len = strlen(str);
		if (_size + len > _capacity)
		{
			reserve(_size + len > 2 * _capacity ? _size + len : 2 * _capacity);
		}
		strcpy(_str + _size, str);
		_size += len;
	}
	string& string::operator+=(const char* str)
	{
		append(str);
		return *this;
	}
	void string::insert(size_t pos, char ch)
	{
		assert(pos <= _size);
		if (_size == _capacity)
		{
			reserve(_capacity == 0 ? 4 : 2 * _capacity);
		}
		size_t end = _size;
		while (end >= pos)
		{
			_str[end + 1] = _str[end];
			end--;
		}
		_str[pos] = ch;
		_size++;
	}
	void string::insert(size_t pos, const char* str)
	{

	}
	void string::erase(size_t pos, size_t len)
	{

	}
	void test_string1()
	{
		string st1;
		string st2("hello world");
		cout << st1.c_str() << endl;
		cout << st2.c_str() << endl;
		for (int i = 0;i < st2.size();i++)
		{
			st2[i] += 2;
		}
		cout << st2.c_str() << endl;
		for (auto e : st2)
		{
			cout << e << " ";
		}
		cout << endl;
		string::iterator it = st2.begin();
		while (it != st2.end())
		{
			cout << *it << " ";
			it++;
		}
		cout << endl;
	}
	void test_string2()
	{
		string st1("hello world");
		st1 += '#';
		st1 += 'k';
		cout << st1.c_str() << endl;
		st1 += "yzk";
		cout << st1.c_str() << endl;
		st1.insert(5, 'k');
		cout << st1.c_str() << endl;
	}
}